const router = require('koa-router')()
const fs = require('fs')
const path = require('path')
const { readableStreamUpload } = require('../../utils/qiniu')
const { qiniuConfig } = require("../../utils/config")
const { resBody } = require("../../utils")
const { bucketDomain } = qiniuConfig

// 文件上传 
// public/upload/
const saveDirPath = path.join(__dirname, '../../public/upload/');
const uploadMethod = async(file, fileName) => {
    const reader = fs.createReadStream(file.path);
    const uploadPath = `${saveDirPath}/${fileName}`;
    const upStream = fs.createWriteStream(uploadPath);
    reader.pipe(upStream);
    return uploadPath;
}

/**
 * 上传的两种方式：
 * 1.上传到服务器,然后将服务器的资源同步七牛云（formUploaderFile）
 *   let uploadPath = await uploadMethod(file, fileName);
 *   let upQN = await formUploaderFile(fileName, uploadPath);
 * 2.不经过服务器,直接将文件流上传到七牛云 （readableStreamUpload）
 *   let reader = fs.createReadStream(file.path);
 *   let upQN = await readableStreamUpload(fileName, reader);
 */


router.post('/', async(ctx) => {
    const file = ctx.request.files.file;
    const nowTime = new Date();
    const fileName = nowTime.getTime() + '.' + file.name.split('.').slice(-1);
    const reader = fs.createReadStream(file.path);
    let upQiNiu = await readableStreamUpload(fileName, reader);
    if (!upQiNiu || !upQiNiu.key) {
        console.log(upQiNiu);
        throw ({
            ...resBody.createFail,
            msg: '上传七牛云出错！'
        });
    }
    let qiniuUrl = `${bucketDomain}/${fileName}`;
    ctx.body = {
        ...resBody.success,
        data: {
            name: fileName,
            url: qiniuUrl
        }
    };
})

module.exports = router